package com.stn.zjx.givingtreasure.activity.intelligence;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.TtsMode;
import com.google.gson.Gson;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.adapter.RobotMsgItemListAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.constants.StnConstants;
import com.stn.zjx.givingtreasure.demo.RobotMsgDomain;
import com.stn.zjx.givingtreasure.domain.AsrSpeechDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.utils.StatusBarUtil;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.stn.zjx.givingtreasure.widget.WhiteVoiceBoView;
import com.vondear.rxtools.RxKeyboardTool;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxSPTool;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class IntelliGenceRobotActivity extends BaseActivity {
    //申请必要权限请求代码
    public final int REQUEST_MAKEFENG_PERMISSION=4405;

    @BindView(R.id.switch_record_bt)
    RelativeLayout switchRecordBt;
    @BindView(R.id.switch_keyboard_bt)
    RelativeLayout switchKeyboardBt;
    @BindView(R.id.send_bt)
    RelativeLayout sendBt;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.robot_head_bg)
    RelativeLayout robotHeadBg;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.audio_iv)
    ImageView audioIv;
    @BindView(R.id.switch_audio_bt)
    RelativeLayout switchAudioBt;
    @BindView(R.id.robot_iv)
    ImageView robotIv;
    @BindView(R.id.body)
    LinearLayout body;
    @BindView(R.id.voice_iv)
    ImageView voiceIv;
    @BindView(R.id.voice_bo)
    WhiteVoiceBoView voiceBo;
    @BindView(R.id.voice_bt)
    RelativeLayout voiceBt;
    private LinearLayoutManager lm;
    private int current = 0;
    SpeechSynthesizer mSpeechSynthesizer;
    RobotMsgItemListAdapter adapter;
    public boolean isKeyboard = false;
    EventManager asr;
    EventListener yourListener;
    private String record_result="";
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initComponent() {
        initStatusBarColor(R.color.black);
        StatusBarUtil.setImmersiveStatusBar(this, false);

        mSpeechSynthesizer = SpeechSynthesizer.getInstance();
//        mSpeechSynthesizer.setSpeechSynthesizerListener(this); //listener
        mSpeechSynthesizer.setContext(this);
        mSpeechSynthesizer.setAppId(StnConstants.Baidu_APP_ID);
        mSpeechSynthesizer.setApiKey(StnConstants.Baidu_APP_KEY, StnConstants.Baidu_APP_SECRET);
        // 设置在线发声音人： 0 普通女声（默认） 1 普通男声 2 特别男声 3 情感男声<度逍遥> 4 情感儿童声<度丫丫>
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");
        // 设置合成的音量，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_VOLUME, "9");
        // 设置合成的语速，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEED, "5");
        // 设置合成的语调，0-9 ，默认 5
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_PITCH, "5");
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT);
        mSpeechSynthesizer.initTts(TtsMode.ONLINE);

        rv.setLayoutManager(lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false));
        rv.setAdapter(adapter = new RobotMsgItemListAdapter(mSpeechSynthesizer, this));



        asr = EventManagerFactory.create(this, "asr"); // this是

         yourListener = new EventListener() {
            @Override
            public void onEvent(String name, String params, byte[] data, int offset, int length) {
                System.out.println("********onEvent*******"+name+"params");
                if(name.equals(SpeechConstant.CALLBACK_EVENT_ASR_READY)){

                    // 引擎就绪，可以说话，一般在收到此事件后通过UI通知用户可以说话了
                }
                  if(name.equals(SpeechConstant.CALLBACK_ASR_RESULT)){

                  }
                  if(name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)){
                      AsrSpeechDomain domain=new Gson().fromJson(params,AsrSpeechDomain.class);
                       if(!TextUtils.isEmpty(domain.getBest_result())){
                           record_result=domain.getBest_result();
                           return;
                       }
                      System.out.println("********CALLBACK_EVENT_ASR_PARTIAL*******"+name+"****"+params+" :"+length);
                  }
                if(name.equals(SpeechConstant.CALLBACK_EVENT_ASR_FINISH)){
                        if(!TextUtils.isEmpty(record_result)){
                            adapter.sendMessage(1, record_result);
                            record_result="";
                            return;
                        }else{
                            record_result="";
                            showToast("声音太小，听不见┭┮﹏┭┮");
                        }

                    // 识别结束
                }
                // ... 支持的输出事件和事件支持的事件参数见“输入和输出参数”一节
            }
        };

        asr.registerListener(yourListener);




        RobotMsgDomain domain = new RobotMsgDomain();
        domain.message_user_type = RobotMsgItemListAdapter.Robot_Header;
        adapter.append(domain);
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        SharedPreferences sp = getSharedPreferences(StnConstants.Audio_OPEN_CLOSE, Context.MODE_PRIVATE);
        if (sp.getBoolean(StnConstants.Audio_OPEN_CLOSE, true)) {
            audioIv.setImageResource(R.mipmap.white_audio_open);
            ToolsUtils.setAudioOpenClose(this, current);
        } else {
            audioIv.setImageResource(R.mipmap.white_audio_close);
            ToolsUtils.setAudioOpenClose(this, 0);

        }

        if (isKeyboard) {
            switchKeyboardBt.setVisibility(View.GONE);
            switchRecordBt.setVisibility(View.VISIBLE);
            RxKeyboardTool.showSoftInput(this, contentEdit);
            voiceBt.setVisibility(View.GONE);
            contentEdit.setVisibility(View.VISIBLE);
            sendBt.setVisibility(View.VISIBLE);
        } else {

            switchRecordBt.setVisibility(View.GONE);
            switchKeyboardBt.setVisibility(View.VISIBLE);
            RxKeyboardTool.hideSoftInput(this, contentEdit);

            contentEdit.setVisibility(View.GONE);
            sendBt.setVisibility(View.GONE);
            voiceBt.setVisibility(View.VISIBLE);
        }

        voiceBt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                System.out.println("***********************motionEvent"+motionEvent.toString());
                  switch (motionEvent.getAction()){
                      case MotionEvent.ACTION_DOWN:
                          methodRequiresTwoPermission();
                          break;
                      case MotionEvent.ACTION_UP:
                          System.out.println("***********************ACTION_UP");
                          voiceBo.setVisibility(View.GONE);
                          voiceIv.setVisibility(View.VISIBLE);
                          asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0); // 发送停止录音事件，提前结束录音等待识别结果
                          return  false;
                  }
                return true;
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intelligence_robot);
        ButterKnife.bind(this);
        initComponent();
        if (!RxNetTool.isNetworkAvailable(this)) {
            showToast1(getString(R.string.internet_conn_error), Gravity.CENTER, 3,0,0);
        } else {
            adapter.sendMessage(0, "Hi,我是您的智能助理小送。我可以推荐您需要的商品和服务");
            rv.smoothScrollToPosition(adapter.dataBeanList.size() - 1);
        }
    }

    @OnClick({R.id.send_bt, R.id.back_bt, R.id.switch_audio_bt,
            R.id.switch_keyboard_bt, R.id.switch_record_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.send_bt:
                if (TextUtils.isEmpty(contentEdit.getText().toString().trim())) {
                    showToast(getString(R.string.want_say_is_not));
                    return;
                }
                adapter.sendMessage(1, contentEdit.getText().toString().trim());
                contentEdit.getText().clear();
                SoftInputUtils.closedSoftInput(this);
                rv.smoothScrollToPosition(adapter.dataBeanList.size() - 1);
                break;
            case R.id.back_bt:
                finish();
                break;
            case R.id.switch_audio_bt:
                SharedPreferences sp = getSharedPreferences(StnConstants.Audio_OPEN_CLOSE, Context.MODE_PRIVATE);
                if (sp.getBoolean(StnConstants.Audio_OPEN_CLOSE, true)) {
                    audioIv.setImageResource(R.mipmap.white_audio_close);
                    ToolsUtils.setAudioOpenClose(this, 0);
                    RxSPTool.putBoolean(this, StnConstants.Audio_OPEN_CLOSE, false);
                } else {
                    audioIv.setImageResource(R.mipmap.white_audio_open);
                    ToolsUtils.setAudioOpenClose(this, current);
                    RxSPTool.putBoolean(this, StnConstants.Audio_OPEN_CLOSE, true);
                }
                break;
            case R.id.switch_keyboard_bt:
                isKeyboard = true;
                switchKeyboardBt.setVisibility(View.GONE);
                switchRecordBt.setVisibility(View.VISIBLE);
                RxKeyboardTool.showSoftInput(this, contentEdit);
                voiceBt.setVisibility(View.GONE);
                contentEdit.setVisibility(View.VISIBLE);
                sendBt.setVisibility(View.VISIBLE);
                break;
            case R.id.switch_record_bt:
                isKeyboard = false;
                switchRecordBt.setVisibility(View.GONE);
                switchKeyboardBt.setVisibility(View.VISIBLE);
                RxKeyboardTool.hideSoftInput(this, contentEdit);

                contentEdit.setVisibility(View.GONE);
                sendBt.setVisibility(View.GONE);
                voiceBt.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToolsUtils.setAudioOpenClose(this, current);
        mSpeechSynthesizer.stop();
        mSpeechSynthesizer.release();
        if(asr!=null&&yourListener!=null){
            asr.unregisterListener(yourListener);
            asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);  // 取消识别
        }


    }


    /**
     * 发送请求权限
     */
    @AfterPermissionGranted(REQUEST_MAKEFENG_PERMISSION)
    public void methodRequiresTwoPermission() {
        //相机，存储，定位，网络状态
        String[] perms = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.RECORD_AUDIO
        };
        //是否有以上权限
        if (EasyPermissions.hasPermissions(this, perms)) {
            showToast1("您的小送正在吟听，请讲话....",Gravity.CENTER,0,0,-100);
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(200);
            System.out.println("***********************ACTION_DOWNACTION_MOVE");
            voiceIv.setVisibility(View.GONE);
            voiceBo.setVisibility(View.VISIBLE);

            Map<String, Object> params=new HashMap<>();
            params.put(SpeechConstant.PID, "1536"); //
            params.put(SpeechConstant.DECODER, "0"); //
            //     params.put(SpeechConstant.IN_FILE, getCacheDir().getPath()+"/inputfile.pcm"); //
            //   params.put(SpeechConstant.ACCEPT_AUDIO_DATA, true); // 目前必须开启此回掉才嫩保存音频
            // params.put(SpeechConstant.OUT_FILE,getCacheDir().getPath()+"/outfile.pcm"); // 目前必须开启此回掉才嫩保存音频

            String json = new JSONObject(params).toString();
            asr.send(SpeechConstant.ASR_START, json, null, 0, 0);
        } else {
            //发起请求权限
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc),
                    REQUEST_MAKEFENG_PERMISSION, perms);
        }

    }

}
